const { Util } = require("./util")
const { aesUtil } = require("./common");

// 小程序开发api接口统一配置
// const API_SNZO_URL = 'http://192.168.0.27:8080' // 神州网PC本地测试域名
// const API_SNZO_URL = 'https://www.snzo.cn:8080/officialTest' // 神州网PC测试域名
const API_SNZO_URL = 'https://www.snzo.cn:8080' // 神州网PC域名
const API_SNZO_FILE_URL = 'https://www.snzo.cn:8080' // 神州网PC域名
const API_ASIAPD_URL = 'https://aa.snzo.cn' // 神通艺术PC域名
const API_MEAL_URL = 'https://contest.snzo.cn' // knowledge项目域名
const asiapdSubUrl = '/digital' //神通艺术项目域名
const API_UC_URL = 'https://uc.snzo.cn' // 用户中心域名
const API_IMAGE_URL = 'https://jfad.snzo.cn' //图片资源域名
let cacheRequest = null;
let Authorization = null;
const request = (url, method, data, header = {
  'Content-Type': 'application/json'
}) => {
  Authorization = wx.getStorageSync('token');
  if (Authorization) {
    header = Object.assign(header, {
      Authorization
    });
  }
  return new Promise((resolve, reject) => {
    wx.request({
      url,
      method,
      data,
      header,
      success: (request) => {
        if (request.data.code === 501) {
          wx.clearStorage();
          cacheRequest = {
            url,
            method,
            data,
            header
          };
          login().then(res => {
            resolve(res)
          }).catch(reject)
          return;
        }
        if (!Authorization && request.header.Authorization) {
          Authorization = request.header.Authorization;
          wx.setStorageSync('Authorization', Authorization)
        }
        resolve(request.data)
      },
      fail: (error) => {
        reject(error)
      },
      complete: (aaa) => {
        // 加载完成
      }
    })
  })
}

/**
 * 微信登录 获取凭证code
 */
const login = () => {
  return new Promise((resolve, reject) => {
    wx.login({
      success: (res) => {
        if (res.code) {
          wxGrant({
            jsCode: res.code
          }).then(res => {
            if (!cacheRequest) {
              resolve(res)
            } else {
              if (Authorization) {
                sendCacheRequest().then(res => {
                  resolve(res)
                }).catch((err) => {
                  reject(err)
                })
              } else {
                wx.navigateTo({
                  url: '/pages/login/login',
                })
                // resolve(res)
              }
            }

          }).catch(err => {
            reject(err)
          })
        }
      },
      fail: (err) => {
        reject(err.errMsg)
      }
    })
  })
}

/**
 * 微信授权用户
 * @param {*} data 
 */
function wxGrant(data) {
  return new Promise((resolve, reject) => {
    request(API_BASE_URL + subDomain + '/wx/grant', 'post', data).then(res => {
      if (res.code === 0 || res.code === 301) {
        wx.setStorageSync('userInfo', JSON.stringify(res.data))
        resolve(res.data);
      } else {
        reject(res.msg);
      }
    }).catch(reject)
  })
}

/**
 * 发送缓存请求
 */
function sendCacheRequest() {
  return new Promise((resolve, reject) => {
    const {
      url,
      method,
      data,
      header
    } = cacheRequest;
    request(url, method, data, header).then(res => {
      cacheRequest = null;
      resolve(res)
    }).catch(reject);
  })
}

/**
 * 小程序的promise没有finally方法，自己扩展下
 */
Promise.prototype.finally = function (callback) {
  var Promise = this.constructor;
  return this.then(
    function (value) {
      Promise.resolve(callback()).then(
        function () {
          return value;
        }
      );
    },
    function (reason) {
      Promise.resolve(callback()).then(
        function () {
          throw reason;
        }
      );
    }
  );
}

// 手机号/身份证号/神州卡号 密码进行登录操作
function ValidateCardByPass(params) {
  const encryptKey = '1kQdPy54X23VjXT7f9nl6d4f2m8238ET';
  const aesRandomKey = aesUtil.getKey();
  const aesKey = aesUtil.encrypt(aesRandomKey, encryptKey);
  const data = aesUtil.encrypt(params, aesRandomKey);
  const bodyParams = {
    aesKey,
    data,
    timestamp: new Date().getTime().toString()
  }
  const headers = {
    'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
  };
  return request(API_UC_URL + '/api/uc/user/ValidateCardByPass', 'post', bodyParams, headers)
}

// 手机号-验证码 进行登录操作
function loginByPhoneAndCode(bodyParams) {
  const headers = {
    'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
  };
  return request(API_UC_URL + '/api/uc/user/loginByPhoneAndCode', 'post', bodyParams, headers)
}

/**
 * 注册用户
 * @param {*} params 
 */
function ValidateAddUser(params) {
  const encryptKey = '1kQdPy54X23VjXT7f9nl6d4f2m8238ET';
  const aesRandomKey = aesUtil.getKey();
  const aesKey = aesUtil.encrypt(aesRandomKey, encryptKey);
  const data = aesUtil.encrypt(params, aesRandomKey);
  const bodyParams = {
    aesKey,
    data,
    timestamp: new Date().getTime().toString()
  }
  const headers = {
    'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
  };
  return request(API_UC_URL + '/api/uc/user/ValidateAddUser', 'post', bodyParams, headers)
}

/**
 * 退出登录
 * @param {*} cardNo 
 * @param {*} token 
 */
function logout(cardNo) {
  return request(API_UC_URL + '/api/uc/user/logout/' + cardNo, 'get')
}

module.exports = {
  API_ASIAPD_URL,
  API_SNZO_URL,
  API_UC_URL,
  API_IMAGE_URL,
  API_SNZO_FILE_URL,
  Authorization,
  request,
  login,
  ValidateCardByPass,
  loginByPhoneAndCode,
  ValidateAddUser,
  logout,
  // 验证token
  isToken: () => request(API_UC_URL + '/api/uc/common/isToken', 'post', ''),
  // 获取openId
  getMiniOpenId: (data, headers) => request(API_MEAL_URL + '/knowledge/wxV3/mini/getMiniOpenId', 'post', data, headers),
  // 发送手机号验证码 1=注册短信类型 2=登录短信类别 3=更新用户短信类别
  sendSms: (phone, data, headers) => request(API_UC_URL + '/api/common/sendSms/' + phone, 'post', data, headers),
  // 获取用户基础信息
  queryCardInfo: (data, headers) => request(API_UC_URL + '/api/uc/user/queryCardInfo', 'post', data, headers),
  // 获取用户交易记录
  queryUserTransaction: (data, headers) => request(API_UC_URL + '/api/uc/user/transaction/queryV2', 'post', data, headers),
  // 获取用户账户详情
  getWalletLogList: (data) => request(API_MEAL_URL + '/knowledge/api/getWalletLogList', 'post', data),
  // 获取用户基础信息
  getWalletBystk: data => request(API_MEAL_URL + '/knowledge/api/getWalletBystk', 'post', data),
  // 校验用户是否是集团用户
  selectUnitUserByStk: data => request(API_SNZO_URL + '/unitUser/selectByStk', 'get', data),
  // 上传头像
  uploadUserImg: data => request(API_UC_URL + '/api/uc/user/uploadUserImg', 'post', data),
  // 获取亚太数字新闻内容
  getNewsMsgById: data => request(API_ASIAPD_URL + asiapdSubUrl + '/speNews/getSpeNewsMsgById', 'get', data),
  // 获取神州网新闻内容
  getSnzoNewsMsgById: data => request(API_SNZO_URL + '/news/getNewsMsgById', 'get', data),
  // 获取新闻列表
  getSpeNewsTitleByLid: (data, pageParams) => request(API_ASIAPD_URL + asiapdSubUrl + '/speNews/getSpeNewsTitleByLid?pageNum=' + pageParams.pageNum + '&pageSize=' + pageParams.pageSize, 'post', data),
  // 获取艺术品类别
  getStNumWorksType: data => request(API_SNZO_URL + '/list/getStNumWorksType', 'post', data),
  // 获取艺术品列表
  selectWorksByExample: (data, params) => request(`${API_SNZO_URL}/worksAndMsg/selectByExampleAndPage?${params}`, 'post', data, { params }),
  // 获取艺术品列表
  selectByPass: (data, params) => request(`${API_SNZO_URL}/worksAndMsg/selectByPass?${params}`, 'post', data, { params }),
  // 获取艺术品交易列表
  selectDealPage: (data, params) => request(`${API_SNZO_URL}/worksAndMsg/selectDealPage?${params}`, 'post', data, { params }),
  // 获取购买商品
  worksBuyLog: (data, pageParams) => request(API_SNZO_URL + '/worksBuyLog/selectByExampleAndPage?pageNum=' + pageParams.pageNum + '&pageSize=' + pageParams.pageSize, 'post', data),
  // 获取卖出商品
  worksSellLog: (data, pageParams) => request(API_SNZO_URL + '/worksSellLog/selectByExampleAndPage?pageNum=' + pageParams.pageNum + '&pageSize=' + pageParams.pageSize, 'post', data),
  // 查询委托书
  selectEntrustMsg: (data, pageParams) => request(API_SNZO_URL + '/entrustMsg/selectByExampleAndPageFront?pageNum=' + pageParams.pageNum + '&pageSize=' + pageParams.pageSize, 'post', data),
  // 按条件查询集团用户
  selectUnitByExample: data => request(API_SNZO_URL + '/unitUser/selectByExample', 'get', data),
  // 获取所有集团用户
  selectUnitAll: data => request(API_SNZO_URL + '/unitUser/selectAll', 'get', data),
  // 按ID查询艺术品
  selectWorksById: data => request(API_SNZO_URL + '/worksAndMsg/selectById', 'get', data),
  // 获取用户空间信息
  selectSpaceMsg: data => request(API_SNZO_URL + '/stNumBuySpLog/selectSpaceMsg', 'get', data),
  // 添加艺术品
  inserWorks: data => request(API_SNZO_URL + '/worksAndMsg/InsertWorks', 'post', data),
  // 申请评价
  askFor: (data, params) => request(API_SNZO_URL + '/worksAndMsg/askFor?stk=' + params.stk, 'post', data),
  // 申请认证
  askAuth: (data, params) => request(API_SNZO_URL + '/worksAndMsg/askAuth?stk=' + params.stk, 'post', data),
  // 上架艺术品 
  transactionWorks: (data) => request(API_SNZO_URL + '/worksAndMsg/transactionWorks', 'post', data),
  //校验上架艺术品状态是否可以修改上架艺术品价格  
  updatePriceBeforeCheck: (data) => request(API_SNZO_URL + '/worksAndMsg/updatePriceBeforeCheck', 'post', data),
  // 获取套餐
  getPackAges: (packageType) => request(API_MEAL_URL + '/knowledge/packageapi/packAges/' + packageType, 'post'),
  // 购买套餐
  wxMiniPayV3: (data) => request(API_MEAL_URL + '/knowledge/wxV3/mini/wxMiniPayV3', 'post', data),
  // 购买前验证
  buyBeforeVerify: (data) => request(API_SNZO_URL + '/worksAndMsg/buyBeforeVerify', 'get', data),
  // 获取openId
  grantMiniPay: (data) => request(API_SNZO_URL + '/StNumMiniPay/grant?jcCode=' + data.jsCode, 'post', ''),
  // 立即支付购买艺术品
  wxApplyMiniPay: (data, body) => request(API_SNZO_URL + '/StNumMiniPay/wxApply?stk=' + data.stk + '&openId=' + data.openId + '&worksId=' + data.worksId + '&dealType=' + data.dealType, 'post', body),
  // 议价支付购买艺术品
  wxApplyMiniPayBargain: (data, body) => request(API_SNZO_URL + '/StNumMiniPay/wxApply?stk=' + data.stk + '&openId=' + data.openId + '&worksId=' + data.worksId + '&bargaining=' + data.bargaining + '&dealType=' + data.dealType + '&bargainCause=' + data.bargainCause ?? '', 'post', body),
  // 认证支付
  authFeeXcxPay: (data, body) => request(API_SNZO_URL + '/StNumMiniPay/authFeeXcxPay?stk=' + data.stk + '&openId=' + data.openId, 'post', body),
  // 提现
  addTixianDraw: (data) => request(API_MEAL_URL + '/knowledge/api/user/addTixian_draw', 'post', data),
  // 填写物流信息
  updateWorksSellLog: data => request(API_SNZO_URL + '/worksSellLog/update', 'post', data),
  // 获取地址列表
  getUserAddress: (data, headers) => request(API_UC_URL + '/api/uc/user/address/list', 'post', data, headers),
  // 新增收货地址
  addUserAddress: data => request(API_UC_URL + '/api/uc/user/address/add', 'post', data),
  // 修改收货地址
  editUserAddress: data => request(API_UC_URL + '/api/uc/user/address/edit', 'post', data),
  // 修改默认收货地址
  editDefaultAddress: data => request(API_UC_URL + '/api/uc/user/address/editDefaultAddress', 'post', data),
  // 删除地址列表
  removeUserAddress: data => request(API_UC_URL + '/api/uc/user/address/remove', 'post', data),
  // 同意/不同意议价
  yesOrNoDeal: data => request(API_SNZO_URL + '/StNumPay/yesOrNoDeal', 'post', data),
  // 委托买卖
  insertEntrust: data => request(API_SNZO_URL + '/entrustMsg/InsertEntrust', 'post', data),
  // 委托前校验
  entrustBeforeVerfity: data => request(API_SNZO_URL + '/entrustMsg/entrustBeforeVerfity', 'post', data),
  // 委托出售
  activeEntrustSell: data => request(API_SNZO_URL + '/entrustMsg/activeEntrustSell', 'post', data),
  // 撤销委托
  entrustRetreat: (params) => request(API_SNZO_URL + '/entrustMsg/entrustRetreat', 'get', params),
  // 意向购买
  addPurpose: (data) => request(API_SNZO_URL + '/purpose/addPurpose', 'post', data),
  // 查询当前用户意向购买列表
  selectPurposeFront: (data, pageParams) => request(API_SNZO_URL + '/purpose/selectPurposeFront?pageNum=' + pageParams.pageNum + '&pageSize=' + pageParams.pageSize, 'post', data),
  // 获取短信验证码
  sendAuthCodeSms: data => request(API_UC_URL + '/api/common/sendAuthCodeSms', 'post', data,),
  // 验证短信验证码
  verifySmsCode: data => request(API_UC_URL + '/api/common/verifySmsCode', 'post', data),
  // 确认交易 被动委托卖出 先验证短信 0-拒绝 1-同意
  yesOrNoSellPassiveEntrust: (params) => request(API_SNZO_URL + '/entrustMsg/yesOrNoSellPassiveEntrust', 'get', params),
  // 确认交易  被动委托购买  先验证短信  0-拒绝 1-同意
  yesOrNoBuyPassiveEntrust: (params) => request(API_SNZO_URL + '/entrustMsg/yesOrNoBuyPassiveEntrust', 'get', params),
  // 修改价格
  updateEntrustPriceBeforePush: (params) => request(API_SNZO_URL + '/entrustMsg/updateEntrustPriceBeforePush', 'get', params),
  // 发送短信
  sendNotifySms: params => request(API_UC_URL + '/api/common/sendNotifySms', 'post', params),
  // 获取艺术品真实路径
  selectRealPathById: (params) => request(API_SNZO_URL + '/worksAndMsg/selectRealPathById', 'get', params),
  // 委托支付
  entrustXcxPay: (data, params) => request(API_SNZO_URL + '/StNumMiniPay/entrustXcxPay?openId=' + data.openId, 'post', params),
  // 关联推广用户
  promoteUser: data => request(API_UC_URL + '/api/uc/common/promoteUser', 'post', data),
  // 获取交流活动列表
  selectArtActiveByCondi: (body, pageParams = { pageNum: 1, pageSize: 999 }) => request(API_SNZO_URL + '/artActive/selectByCondi?pageNum=' + pageParams.pageNum + '&pageSize=' + pageParams.pageSize, 'post', body),
  // 获取交易会活动场次
  selectArtVenueByCondi: (body, pageParams = { pageNum: 1, pageSize: 999 }) => request(API_SNZO_URL + '/artVenue/selectByCondi?pageNum=' + pageParams.pageNum + '&pageSize=' + pageParams.pageSize, 'post', body),
  // 获取交易会活动项目
  getStnumArtItemList: (params) => request(API_SNZO_URL + '/list/getStnumArtItemList', 'get', params),
  // 按ID查询交流活动详情
  selectArtActiveById: (params) => request(API_SNZO_URL + '/artActive/selectOneById?id=' + params.id, 'post'),
  //按ID查询交流活动会场详情
  selectArtVenueById: (params) => request(API_SNZO_URL + '/artVenue/selectOneById?id=' + params.id, 'post'),
  // 交流活动报名支付
  wxPayEnrollFee: (url, data, body) => request(API_SNZO_URL + url + '?payType=' + data.payType + '&openId=' + data.openId, 'post', body),
  // 查询报名状态
  getArtEnrollStatus: data => request(API_SNZO_URL + '/artEnroll/getArtEnrollStatus?stk=' + data.stk, 'post', ''),
  // 查询报名状态(新)
  getArtEnrollStatusNew: data => request(API_SNZO_URL + '/artEnroll/getArtEnrollStatusNew', 'post', data),
  // 按条件获取艺术品
  getShowByCondition: (data, pageParams) => request(API_SNZO_URL + '/artDisplay/getShowByCondition?pageNum=' + pageParams.pageNum + '&pageSize=' + pageParams.pageSize, 'post', data),
  // 按条件获取艺术品
  getArtShowMsgByPayStatus: (data, pageParams) => request(API_SNZO_URL + '/artDisplay/getArtShowMsgByPayStatus?pageNum=' + pageParams.pageNum + '&pageSize=' + pageParams.pageSize, 'post', data),
  // 按条件获取艺术品
  checkSignUpArt: (data) => request(API_SNZO_URL + '/artDisplay/checkSignUpArt', 'post', data),
  // 按ID查询场次信息
  selectArtPeriodByCondi: (data, pageParams) => request(API_SNZO_URL + '/artPeriod/selectByCondi?pageNum=' + pageParams.pageNum + '&pageSize=' + pageParams.pageSize, 'post', data),
  // 获取获奖作品
  getAwardedArtworks: (data, pageParams) => request(API_SNZO_URL + '/artDisplay/getAwardedArtworks?pageNum=' + pageParams.pageNum + '&pageSize=' + pageParams.pageSize, 'post', data),
  // 获取活动资讯列表
  getArtActivityNewsList: (data, pageParams) => request(API_SNZO_URL + '/artActiveNews/getNewsTitleByLid?pageNum=' + pageParams.pageNum + '&pageSize=' + pageParams.pageSize, 'post', data),
  // 获取活动资讯内容
  getArtActivityNews: (data) => request(API_SNZO_URL + '/artActiveNews/getNewsMsgById', 'get', data),
  // 校验用户缴费状态及上传艺术品数量
  artEnrollLsSum: data => request(API_SNZO_URL + '/artEnroll/lsSum?payType=WX', 'post', data),
  // 上传艺术品
  artEnrollLsUpload: data => request(API_SNZO_URL + '/artEnroll/lsUpload?payType=WX', 'post', data),
  // 显示支付钱
  artEnrollLsBufei: data => request(API_SNZO_URL + '/artEnroll/lsBufei?payType=WX', 'post', data),
  // 报名缴费
  // getArtActivityNewsList: (data, payType) => request(API_SNZO_URL + '/artEnroll/lsPayEnrollFee?payType=' + payType, 'post', data),
}